package com.suxin.socket.yinfei;

import com.suxin.socket.yinfei.session.SessionConnectionHolder;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;

/**
 * @author Tang
 * @classname AbstractWebSocketConnection
 * @description [ Socket 模板 ]
 * @date 2021/8/17 22:14
 */
@Slf4j
public abstract class AbstractWebSocketConnection {

    private SessionConnectionHolder sessionConnectionHolder;

    @OnOpen
    public void onOpen(Session session) {
        log.info("新来了一个socket连接:{}", session.getId());
        getSessionConnectionHolder().onOpen(session);
    }

    @OnClose
    public void onClose(Session session) {
        log.info("关闭socket连接id:{}", session.getId());
        getSessionConnectionHolder().onClose(session);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("session id:[{}]收到的数据为:{}", session.getId(), message);
    }

    /**
     * 发送数据
     * @param message message
     * @param session session
     */
    public static void sendMsg(String message, Session session) {
        if (session.isOpen()) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                log.info("数据发送异常:{}", e);
            }
        }
    }

    /**
     * 获取一个抽象的 session holder
     *
     * @return
     */
    protected abstract SessionConnectionHolder getSessionConnectionHolder();

}